package com.yxkj.railservicer.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.application.MyApplication;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.RSAPublicUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.ScreenUtils;
import com.yxkj.railservicer.util.SysApplicationUtil;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ForgetActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TAG";

    private ImageView iv_main_back;
    private TextView tv_title;
    private ImageView iv_main_setting;
    private EditText et_forget_name;
    private EditText et_forget_auth;
    private EditText et_password;
    private EditText et_pw_confirm;
    private Button btn_forget_auth;
    private Button btn_forget;

    private OkHttpClient client;
    private JSONUtil jsonUtil;

    private ProgressDialog dialog;

    private int countSeconds = 60;//倒计时秒数
    private Handler mCountHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (countSeconds > 0) {
                --countSeconds;
                btn_forget_auth.setText("(" + countSeconds + ")后获取验证码");
                mCountHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                countSeconds = 60;
                btn_forget_auth.setText("请重新获取验证码");
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#2387f5"));
        SysApplicationUtil.getInstance().addActivity(this);
        initData();
        initEvent();
    }

    /**
     * 加载事件
     */
    private void initEvent() {
        iv_main_setting.setVisibility(View.INVISIBLE);
        tv_title.setText("找回密码");
        iv_main_back.setOnClickListener(this);
        btn_forget_auth.setOnClickListener(this);
        btn_forget.setOnClickListener(this);
    }

    /**
     * 加载数据
     */
    private void initData() {
        iv_main_back = (ImageView) findViewById(R.id.iv_main_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_main_setting = (ImageView) findViewById(R.id.iv_main_setting);
        et_forget_name = (EditText) findViewById(R.id.et_forget_name);
        et_forget_auth = (EditText) findViewById(R.id.et_forget_auth);
        et_password = (EditText) findViewById(R.id.et_password);
        et_pw_confirm = (EditText) findViewById(R.id.et_pw_confirm);
        btn_forget_auth = (Button) findViewById(R.id.btn_forget_auth);
        btn_forget = (Button) findViewById(R.id.btn_forget);

        client = new OkHttpClient();

        jsonUtil = new JSONUtil();
    }

    /**
     * 点击事件
     *
     * @param v
     */

    private String password ;
    private String password_real ;
    private String code;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //返回
            case R.id.iv_main_back :
                finish();
                break;
            //获取验证码
            case R.id.btn_forget_auth :
                getAuth();
                break;
            //确定重置
            case R.id.btn_forget :
                password = et_password.getText().toString();
                password_real = et_pw_confirm.getText().toString();
                code = et_forget_auth.getText().toString();
                if (judgePassword(password,password_real)) {
                    getRSA();

                }else {
                    toast("输入密码不一致");
                }
                break;
        }
    }

    /**
     * 确定重置
     */
    private void confirm() {
        String newPassword = RSAPublicUtil.publicEncryptString(modulus, exponent, code + password);
        String change = "?code=" + code + "&phoneNo=" + phoneNo + "&newPassword=" + newPassword;

        if(token == null){
            token = "aaa";
        }
        Request request = new Request.Builder()
                .addHeader("token",token)
                .url(ContentUtil.message_change_url + change)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "重置密码联网成功" );
                String dataMessage = response.body().string();
                Log.e(TAG, "onResponse: " + dataMessage );
                if (jsonUtil.validate(dataMessage)) {

                    JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Intent intent = new Intent(ForgetActivity.this,LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    private String modulus;
    private String exponent;

    private void getRSA() {
        dialog = ProgressDialog.show(this,"提示","正在连接服务器，请稍后");
        Request request = new Request.Builder()
                .url(ContentUtil.RSA_url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        modulus = jsonObject.getJSONObject("data").getString("modulus");
                        exponent = jsonObject.getJSONObject("data").getString("exponent");
                        confirm();
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
                Log.e(TAG, "RSA登录联网成功" + jsonData);
            }


        });
    }



    private String phoneNo;
    /**
     * 获取验证码
     */
    private void getAuth() {
        if (countSeconds == 60) {
            phoneNo = et_forget_name.getText().toString();
            Log.e("tag", "phoneNo==" + phoneNo);
            getMobiile(phoneNo);
        } else {
            toast("不能重复发送验证码");
        }

    }

    //使用正则表达式判断电话号码
    public static boolean isMobileNO(String tel) {
        Pattern p = Pattern.compile("^(13[0-9]|15([0-3]|[5-9])|14[5,7,9]|17[1,3,5,6,7,8]|18[0-9])\\d{8}$");
        Matcher m = p.matcher(tel);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    //获取验证码信息,进行计时操作
    private void startCountBack() {
        (this).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_forget_auth.setText(countSeconds + "");
                mCountHandler.sendEmptyMessage(0);
            }
        });
    }

    //获取验证码信息，判断是否有手机号码
    private void getMobiile(String mobile) {
        if ("".equals(mobile)) {
            Log.e("tag", "phoneNo=" + mobile);
            new AlertDialog.Builder(this).setTitle("提示").setMessage("手机号码不能为空").setCancelable(true).show();
        } else if (!isMobileNO(mobile)) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("请输入正确的手机号码").setCancelable(true).show();
        } else {
            Log.e("tag", "输入了正确的手机号");
            requestVerifyCode(mobile);
        }
    }
    private String notes;
    private String token;
    //获取验证码信息，进行验证码请求
    private void requestVerifyCode(String phoneNo) {
        dialog = ProgressDialog.show(this,"提示","正在获取验证码，请稍后");
        String message = "?phoneNo=" + phoneNo;
        Request request = new Request.Builder()
                .url(ContentUtil.message_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                startCountBack();
                String dataMessage = response.body().string();
                if (jsonUtil.validate(dataMessage)) {
                    Log.e("TAG", dataMessage);
                    JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(ForgetActivity.this, "token", token);

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    //打印TAG
    private void toast(final String string){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ForgetActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }
    private Boolean judgePassword(String password, String password_real){
        if(password.equals(password_real)){
            return true;
        } else {
            return false;
        }
    }
    private void dismiss(){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SysApplicationUtil.getInstance().deleteActivity(this);
    }
}
